package org.example.wx.user.web;

import lombok.Data;
import org.example.wx.user.entity.ShippingAddress;
import org.example.wx.user.service.ShippingAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/wx/address")
public class ShippingAddressController {

    @Autowired
    private ShippingAddressService shippingAddressService;

    /**
     * 获取用户所有收货地址
     */
    @GetMapping("/list")
    public ResponseEntity<?> getUserAddresses(@RequestHeader("Authorization") String token) {
        try {
            Long userId = extractUserIdFromToken(token);
            List<ShippingAddress> addresses = shippingAddressService.getUserAddresses(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", addresses);
            result.put("total", addresses.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取地址列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 根据ID获取地址详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getAddressById(@RequestHeader("Authorization") String token, @PathVariable Long id) {
        try {
            Long userId = extractUserIdFromToken(token);
            Optional<ShippingAddress> addressOpt = shippingAddressService.getAddressById(userId, id);
            
            if (addressOpt.isPresent()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", addressOpt.get());
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "地址不存在");
                return ResponseEntity.badRequest().body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取地址详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 新增收货地址
     */
    @PostMapping("/create")
    public ResponseEntity<?> createAddress(@RequestHeader("Authorization") String token, @RequestBody AddressRequest request) {
        try {
            Long userId = extractUserIdFromToken(token);
            
            // 验证必填字段
            if (request.getRecipientName() == null || request.getRecipientName().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("收货人姓名不能为空"));
            }
            if (request.getPhoneNumber() == null || request.getPhoneNumber().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("手机号不能为空"));
            }
            if (request.getProvince() == null || request.getProvince().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("省份不能为空"));
            }
            if (request.getCity() == null || request.getCity().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("城市不能为空"));
            }
            if (request.getCounty() == null || request.getCounty().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("区县不能为空"));
            }
            if (request.getDetailedAddress() == null || request.getDetailedAddress().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("详细地址不能为空"));
            }
            
            ShippingAddress address = new ShippingAddress();
            address.setRecipientName(request.getRecipientName());
            address.setPhoneNumber(request.getPhoneNumber());
            address.setProvince(request.getProvince());
            address.setCity(request.getCity());
            address.setCounty(request.getCounty());
            address.setDetailedAddress(request.getDetailedAddress());
            address.setAddressTag(request.getAddressTag() != null ? request.getAddressTag() : "家");
            address.setIsDefault(request.getIsDefault() != null ? request.getIsDefault() : false);
            
            ShippingAddress createdAddress = shippingAddressService.createAddress(userId, address);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "地址创建成功");
            result.put("data", createdAddress);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "创建地址失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 更新收货地址
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateAddress(@RequestHeader("Authorization") String token, 
                                         @PathVariable Long id, 
                                         @RequestBody AddressRequest request) {
        try {
            Long userId = extractUserIdFromToken(token);
            
            // 验证必填字段
            if (request.getRecipientName() == null || request.getRecipientName().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("收货人姓名不能为空"));
            }
            if (request.getPhoneNumber() == null || request.getPhoneNumber().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("手机号不能为空"));
            }
            
            ShippingAddress address = new ShippingAddress();
            address.setRecipientName(request.getRecipientName());
            address.setPhoneNumber(request.getPhoneNumber());
            address.setProvince(request.getProvince());
            address.setCity(request.getCity());
            address.setCounty(request.getCounty());
            address.setDetailedAddress(request.getDetailedAddress());
            address.setAddressTag(request.getAddressTag());
            address.setIsDefault(request.getIsDefault());
            
            ShippingAddress updatedAddress = shippingAddressService.updateAddress(userId, id, address);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "地址更新成功");
            result.put("data", updatedAddress);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "更新地址失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 删除收货地址
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAddress(@RequestHeader("Authorization") String token, @PathVariable Long id) {
        try {
            Long userId = extractUserIdFromToken(token);
            boolean deleted = shippingAddressService.deleteAddress(userId, id);
            
            if (deleted) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "地址删除成功");
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "地址不存在或删除失败");
                return ResponseEntity.badRequest().body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "删除地址失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/{id}/default")
    public ResponseEntity<?> setDefaultAddress(@RequestHeader("Authorization") String token, @PathVariable Long id) {
        try {
            Long userId = extractUserIdFromToken(token);
            boolean success = shippingAddressService.setDefaultAddress(userId, id);
            
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "默认地址设置成功");
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "地址不存在或设置失败");
                return ResponseEntity.badRequest().body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "设置默认地址失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取默认地址
     */
    @GetMapping("/default")
    public ResponseEntity<?> getDefaultAddress(@RequestHeader("Authorization") String token) {
        try {
            Long userId = extractUserIdFromToken(token);
            Optional<ShippingAddress> defaultAddress = shippingAddressService.getDefaultAddress(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", defaultAddress.orElse(null));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取默认地址失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    private Long extractUserIdFromToken(String token) {
        // 简化token解析逻辑，用于测试
        try {
            if (token == null || token.trim().isEmpty()) {
                // 临时：如果没有token，返回默认用户ID 1
                return 1L;
            }
            
            if (token.startsWith("user-")) {
                return Long.parseLong(token.substring(5));
            } else if (token.startsWith("wx-")) {
                // 临时：微信用户也返回用户ID 1
                return 1L;
            }
            
            // 临时：其他情况也返回用户ID 1
            return 1L;
        } catch (Exception e) {
            // 临时：解析失败时返回默认用户ID 1
            return 1L;
        }
    }

    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("success", false);
        error.put("message", message);
        return error;
    }

    @Data
    public static class AddressRequest {
        private String recipientName;
        private String phoneNumber;
        private String province;
        private String city;
        private String county;
        private String detailedAddress;
        private String addressTag;
        private Boolean isDefault;
    }
}
